# 爬取网站翻应用
# 问题：1. 只输出一个表头 2. 字符串格式化时，不同语言占用显示宽度不同的问题
import requests, time
from bs4 import BeautifulSoup

def req(url):
    headersvalue = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36 Edg/94.0.992.50'}
    r = requests.get(url, headers=headersvalue)
    soup = BeautifulSoup(r.text, 'lxml')
    return soup

def output_content(divs, pnum = 999, update_time=True):
    if update_time:
        print('{:^40} {:^90} {:10}\n{}'.format('软件', '链接', '时间', '='*150))  
    else:
        print('{:^40} {:^90}\n{}'.format('软件', '链接', '='*110))
    n = 0
    for div in divs:
        name, url, ud_time = div.a.string, div.a.attrs['href'], div.div.string
        if update_time:
            print('{:<45} {:^60} {:^15}\n{}'.format(name, url, ud_time, '-'*150))
        else:
            print('{:<45} {:^60}\n{}'.format(name, url, '-'*110))
        n += 1
        if n == pnum:
            break

def update_info():
    # 对于当天更新的内容，输出软件名和链接
    t = time.localtime()
    real_time = '%s月%s日 · %s年' % (t.tm_mon, t.tm_mday, t.tm_year)
    url = 'https://www.iapps.me/archives/category/app'
    node_div = req(url).find_all('div', attrs={'class': 'meta'})
    update_content = [div for div in node_div if div.div.string == real_time]
    n = len(update_content)
    print(f'今天更新了 {n} 个软件\n')
    if n > 0:
        output_content(node_div[:n], update_time=False)
    previous_div = node_div[n:]
    return previous_div

def app(dfp):
    # dfp: div of first page
    print('一般情况下，翻应用一天更新 10 个 app。需要浏览几个？\n')
    num = int(input(''))
    if dfp:
        if len(dfp) < num:
            output_content(dfp)
            pages = int((num-len(dfp))/10)+1
            for page in range(pages):
                page_url = 'https://www.iapps.me/archives/category/app/page/' + str(page+2)
                node_div = req(page_url).find_all('div', attrs={'class': 'meta'})
                output_content(node_div, pnum=num-len(dfp))
        else:
            output_content(dfp[:num])
    else:
        pages = int(num/10)+1
        for page in range(pages):
            page_url = 'https://www.iapps.me/archives/category/app/page/' + str(page+2)
            node_div = req(page_url).find_all('div', attrs={'class': 'meta'})
            output_content(node_div, pnum = num-10)

def main():
    previous_div = update_info()
    answer = input('是否浏览以前的内容？Y/N')
    if answer == 'Y' or 'y':
        app(previous_div)
    
main()








